package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojo.ApUser;
import com.heima.model.user.vo.LoginVo;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.BCrypt;
import org.springframework.stereotype.Service;

@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    /**
     * 登录接口
     *   二合一，用户登录也是有游客登录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {
        String token=null;
        LoginVo loginVo=null;
        if("".equals(dto.getPassword())&&"".equals(dto.getPhone())){
            token = AppJwtUtil.getToken(Long.valueOf(0));
            loginVo = new LoginVo(null,token);
            return ResponseResult.okResult(loginVo);
        }
        ApUser apUser = this.getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));
        if(apUser==null){
            return ResponseResult.errorResult(1002,"用户不存在");
        }else {
            boolean checkpw = BCrypt.checkpw(dto.getPassword(), apUser.getPassword());
            if(!checkpw){
                return ResponseResult.errorResult(2,"密码错误");
            }
            token = AppJwtUtil.getToken(Long.valueOf(apUser.getId()));
            loginVo = new LoginVo(apUser,token);
            return ResponseResult.okResult(loginVo);
        }
    }

    /**
     * 根据用户id获取用户实体
     *
     * @param userId
     * @return
     */
    @Override
    public ResponseResult<ApUser>findUserById(Integer userId) {
        ApUser apUser = getById(userId);
        return ResponseResult.okResult(apUser);
    }
}
